import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpClient {
    private DatagramSocket socket = null;
    private String serverIp = "";
    private int serverPort = 0;

    public UdpClient(String ip, int port) throws SocketException {
        //upd的socket只包含两元祖：自己的ip和自己的port
        //系统会隐式的分配给port
        socket = new DatagramSocket();

        serverIp = ip;
        serverPort = port;
    }

    public void start() throws IOException {
        System.out.println("客户端启动.......");

        while(true){
            //1.发送请求
            System.out.println("请输入：");
            Scanner sc = new Scanner(System.in);
            String request = sc.next();

            //2.将请求内容构造成DatagramPacket对象，发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(
                    request.getBytes(),
                    0,
                    request.getBytes().length,
                    InetAddress.getByName(serverIp),
                    serverPort);
            //发送请求
            socket.send(requestPacket);

            //3.接受服务器的请求
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(responsePacket);

            //4.将服务器的响应显示
            String response = new String(
                    responsePacket.getData(),
                    0,
                    responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        new UdpClient("127.0.0.1", 9090).start();
    }

}
